<template>
  <div class="filter-container">
    <el-select v-model="filterValue.type" class="filter-item" placeholder="请选择浏览方式" @change="handleTypeChange">
      <el-option v-for="item in primaryOptions" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>

    <el-select v-if="filterValue.type !== 'overview'" v-model="filterValue.subType" class="filter-item"
      :placeholder="getSubTypePlaceholder" @change="handleSubTypeChange">
      <el-option v-for="item in currentSubOptions" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
  </div>
</template>

<script setup>
import { useAreaStore } from '@/stores/area';
import { useCompanyStore } from '@/stores/company';
import { useEnergyUsersStore } from '@/stores/energyUser';
import { ref, computed, watch, watchEffect } from 'vue'
let energyUsersStore = useEnergyUsersStore()
let companyStore = useCompanyStore()
let areaStore = useAreaStore()
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      type: 'overview',
      subType: ''
    })
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// 内部状态
const filterValue = ref({
  type: props.modelValue.type,
  subType: props.modelValue.subType
})

// 主选项
const primaryOptions = [
  { value: 'overview', label: '总览' },
  { value: 'byEnergyUser', label: '按用能户浏览' },
  { value: 'byArea', label: '按区域浏览' },
]

// 改为响应式对象
const subOptions = ref({
  byArea: computed(() => areaStore.areas.map(item => ({
    value: item.id,
    label: item.name
  }))),
  byEnergyUser: computed(() => energyUsersStore.energyUserList.map(item => ({
    value: item.id,
    label: item.name
  })))
})

// 计算次级选项
const currentSubOptions = computed(() => {
  return subOptions.value[filterValue.value.type]
})

// 计算次级选项占位符
const getSubTypePlaceholder = computed(() => {
  const placeholders = {
    byArea: '请选择区域',
    byType: '请选择用水类型',
    byEnergyUser: '请选择用能户'
  }
  return placeholders[filterValue.value.type] || '请选择'
})

// 处理主类型变化
const handleTypeChange = () => {
  filterValue.value.subType = ''
  updateValue()
}

// 处理次级类型变化
const handleSubTypeChange = () => {
  updateValue()
}

// 更新值并触发事件
const updateValue = () => {
  emit('update:modelValue', { ...filterValue.value })
  emit('change', { ...filterValue.value })
}

watch(
  () => props.modelValue,
  (newVal) => {
    filterValue.value = { ...newVal }
  },
  { deep: true }
)
watchEffect(async () => {
  await energyUsersStore.fetchEnergyUsers({
    company_id: companyStore.currentCompany.id
  })
})
</script>

<style scoped>
.filter-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-item {
  width: 180px;
}
</style>